package com.lbd.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;


/**
 * Created by wang on 2016/10/25.
 */
public class ExcelExportUtils {
    private static final Logger log = Logger.getLogger(ExcelExportUtils.class);

    /**
     * 1. 导出Excel
     *
     * @param request   request
     * @param response  response
     * @param fileName  导出文件名称
     * @param pojoClass 导出数据对象class
     * @param dataSet   导出数据集
     */
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, Class<?> pojoClass, Collection<?> dataSet) {
        exportExcel(request, response, fileName, null, "sheet1", ExcelType.XSSF, pojoClass, dataSet);
    }

    /**
     * 2. 导出Excel
     *
     * @param request   request
     * @param response  response
     * @param fileName  导出文件名称
     * @param title     导出文件title
     * @param sheetName 导出文件sheetName
     * @param pojoClass 导出数据对象class
     * @param dataSet   导出数据集
     */
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, String title, String sheetName, Class<?> pojoClass, Collection<?> dataSet) {
        exportExcel(request, response, fileName, title, sheetName, ExcelType.XSSF, pojoClass, dataSet);
    }

    /**
     * 3. 导出Excel
     *
     * @param request   request
     * @param response  response
     * @param fileName  导出文件名称
     * @param title     导出文件title
     * @param sheetName 导出文件sheetName
     * @param excelType 导出文件类型
     * @param pojoClass 导出数据对象class
     * @param dataSet   导出数据集
     */
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, String title, String sheetName, ExcelType excelType, Class<?> pojoClass, Collection<?> dataSet) {
        //1.获取参数
        String agent = (String) request.getHeader("USER-AGENT");
        //2.设置参数，并生成文件
        ExportParams exportParams = new ExportParams(title, sheetName, excelType == null ? ExcelType.XSSF : excelType);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, dataSet);
        //3.导出文件
        OutputStream fOut = null;
        try {
            response.setContentType(getFileType(excelType));
            response.setHeader("content-disposition", "attachment;filename=" + getFileName(agent, excelType, fileName));
            // 产生工作簿对象
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            log.info("导出文件异常" + e);
        } finally {
            try {
                if (null != fOut) {
                    fOut.flush();
                    fOut.close();
                }
            } catch (IOException e) {
                log.info("关闭流异常" + e);
            }
        }
    }

    private static String getFileName(String agent, ExcelType excelType, String fileName) {
        //1.设置文件名称
        String fileNameUTF8 = "excel.xlsx";
        try {
            if (null != excelType && excelType == ExcelType.HSSF) {
                if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                    fileNameUTF8 = "=?UTF-8?B?" + (new String(Base64.encodeBase64((fileName + ".xls").getBytes("UTF-8")))) + "?=";
                } else {
                    fileNameUTF8 = java.net.URLEncoder.encode(fileName + ".xls", "UTF-8");
                }
            } else {
                if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                    fileNameUTF8 = "=?UTF-8?B?" + (new String(Base64.encodeBase64((fileName + ".xlsx").getBytes("UTF-8")))) + "?=";
                } else {
                    fileNameUTF8 = java.net.URLEncoder.encode(fileName + ".xlsx", "UTF-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            log.info(e);
        }
        return fileNameUTF8;
    }

    private static String getFileType(ExcelType excelType) {
        //1.设置文件名称
        String fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if (null != excelType && excelType == ExcelType.HSSF) {
            fileType = "application/vnd.ms-excel";
        }
        return fileType;
    }


}
